package com.lcm.basic.p7.set;

import com.lcm.basic.p7.set.bean.TreeSortBean;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * @author Coder-lcm
 * @date 2021/4/3
 *
 *  TressSet有序且唯一的集合
 *      TressSet的元素要求实现Comparable接口，否则就要自己去写匿名的比较器
 *
 */
public class TreeSetDemo {
    public static void main(String[] args) {
        /**
         * 1. 数值比较 ，默认按自然方式排序
         */
        TreeSet<Integer> treeSet = new TreeSet<>();
        treeSet.add(123);
        treeSet.add(34);
        treeSet.add(67);
        treeSet.add(89);
        System.out.println(treeSet); //[34, 67, 89, 123]

        Comparator<? super Integer> comparator = treeSet.comparator();
        System.out.println("treeSet比较器： " + comparator);

        /**
         * 指定按对象的某个属性来排序
         *      使用匿名内部类来自定义对象的排序规则
         */
        TreeSet<TreeSortBean> beanSet = new TreeSet<>();
        beanSet.add(new TreeSortBean(12,"lcm01"));
        beanSet.add(new TreeSortBean(14, "lcm02"));
        beanSet.add(new TreeSortBean(9,"lcm03"));
        beanSet.add(new TreeSortBean(90,"lcm04"));
        System.out.println(beanSet);// [TreeSortBean{num=9, name='lcm03'}, TreeSortBean{num=12, name='lcm01'}, TreeSortBean{num=14, name='lcm02'}, TreeSortBean{num=90, name='lcm04'}]
        System.out.println("beanSet比较器： " + beanSet.comparator()); //com.lcm.basic.p7.set.TreeSetDemo$1@60e53b93

        /**
         * TreeSet的一些特性
         */
        System.out.println(beanSet.first()); // reteurn the first element in treeset
        System.out.println(beanSet.last());
        beanSet.lower(new TreeSortBean(14,"lcm02")); // TreeSortBean{num=9, name='lcm03'}
        beanSet.higher(new TreeSortBean(14,"lcm02")); //TreeSortBean{num=90, name='lcm04'}

        System.out.println(treeSet.subSet(30, 90)); // [34, 67, 89]
        System.out.println(treeSet.headSet(67)); // [34,67,89]
        treeSet.tailSet(89); // [34]
    }
}
